package com.aounhui.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.aounhui.common.entity.Result;
import com.aounhui.common.enums.ResponseEnums;
import com.aounhui.common.exceptions.CreateException;
import com.aounhui.common.utils.MD5Util;
import com.aounhui.common.utils.UUIDUtil;
import com.aounhui.customer.entity.User;
import com.aounhui.customer.entity.UserExample;
import com.aounhui.customer.mapper.UserMapper;
import com.aounhui.customer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional(rollbackFor = CreateException.class)
    public Result userRegister(User user) {
        log.info("创建新用户开始，用户参数:loginName={},userName={}", user.getLoginName(), user.getUserName());
        if (getUsers(user.getLoginName()).getContent().size() == 0) {
            user.setId(UUIDUtil.getUUID());
            try {
                user.setPassword(MD5Util.getEncryptedPwd(user.getPassword()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            user.setCreateTime(new Date());
            int result = userMapper.insertSelective(user);
            if (result == 1) {
                log.info("创建用户“{}”成功", user.getLoginName());
                return Result.ok(user.getLoginName() + "创建成功");
            }
            log.error("{}创建用户失败，执行事物，数据回滚", user.getLoginName());
            throw new CreateException("创建用户失败，创建结果number="+result);
        } else {
            log.error("创建用户失败，{} 用户已经被注册");
            return Result.error(ResponseEnums.ERROR01.getResponseMessage(), "此用户名已被注册");
        }
    }

    @Override
    public Result userLogin(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String loginName = user.getLoginName();
        User userInfoInDb = getUsers(loginName).getContent().get(0);
        log.info("{} 用户尝试登陆", loginName);
        if (MD5Util.validPassword(user.getPassword(), userInfoInDb.getPassword())) {
            log.info("{} 用户密码校验正确，登陆成功", loginName);
            redisTemplate.opsForValue().set(userInfoInDb.getId(), JSON.toJSONString(userInfoInDb));
            return Result.ok(userInfoInDb);
        }
        log.warn("{} 用户密码错误，登陆失败", loginName);
        //TODO error more 3,user lock 30 min
        return Result.error("密码错误，登陆失败");
    }

    @Override
    public Result userUpdate(User user) {
        return null;
    }

    @Override
    public Result UserDelete(String userId) {
        return null;
    }

    @Override
    public Result<List<User>> getUsers(String loginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIsDeleteEqualTo(0);
        criteria.andLoginNameEqualTo(loginName);
        List<User> users = userMapper.selectByExample(userExample);
        return Result.ok(users);
    }

}
